package com.platform.api.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.api.config.mini.ByteMiniApp;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.core.ResultCode;
import com.platform.common.util.ObjectUtil;
import com.platform.common.util.RedisUtil;
import com.platform.common.util.http.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


/**
 * @author guoyunfei on 2021/11/23 17:13
 * @className DouyinService
 * @description TODO
 * @Version 1.0
 */


@Service
@Slf4j
public class ByteService {


    @Autowired
    private ByteMiniApp byteMiniApp;


    /**
     * 抖音授权登录
     * @return
     */
    public Result loginForDy(String code,String anonymous_code) throws IOException {
        if (StringUtils.isEmpty(code) && StringUtils.isEmpty(anonymous_code)) {
            return Result.failure("code || anonymous_code 不能为空");
        }
        JSONObject param = new JSONObject();
        param.put("appid", byteMiniApp.getAppid());
        param.put("secret", byteMiniApp.getSecret());
        param.put("code", code);
        param.put("anonymous_code", anonymous_code);

        String baseDataStr = HttpClientUtil.sendPostReq(Constant.BYTE_LOGIN_URL,param,null);
        log.info(baseDataStr);
        JSONObject baseDataObject = JSON.parseObject(baseDataStr);
        if (baseDataObject.get("data") == null) {
            log.info("获取字节用户基本信息异常 req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
            return Result.failure("获取用户信息失败");
        }
        JSONObject baseData = baseDataObject.getJSONObject("data");
        if (baseData.get("openid") == null || StringUtils.isEmpty(baseData.get("openid").toString())) {
            log.info("获取字节用户基本信息异常 req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
            return Result.failure("获取用户信息失败");
        }
        log.info("获取字节用户基本信息成功 req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
        String openId = baseData.get("openid").toString();

        return Result.success(openId);
    }


    /**
     * 获取access_token 小程序级别唯一凭证，
     * @return
     */
    public Result getAccessToken() throws IOException {

        //redis获取缓存
        Object cache_access_token = RedisUtil.get(Constant.MINI_ACCESS_TOKEN);

        if(!ObjectUtil.isEmpty(cache_access_token)){
            return Result.success(cache_access_token);
        }

        JSONObject param = new JSONObject();
        param.put("appid", byteMiniApp.getAppid());
        param.put("secret", byteMiniApp.getSecret());
        param.put("grant_type", byteMiniApp.getGrant_type());

        String baseDataStr = HttpClientUtil.sendPostReq("https://developer.toutiao.com/api/apps/v2/token",param,null);

        JSONObject baseDataObject = JSON.parseObject(baseDataStr);

        if(baseDataObject.getIntValue("err_no") != 0){
            log.info("获取字节access_token信息异常 req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
            return Result.failure("获取字节access_token信息异常");
        }

        if (baseDataObject.get("data") == null) {
            log.info("获取字节access_token信息异常 req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
            return Result.failure("获取字节access_token信息异常");
        }

        JSONObject baseData = baseDataObject.getJSONObject("data");

        String access_token = baseData.getString("access_token");

        //存入redis缓存
        RedisUtil.set(Constant.MINI_ACCESS_TOKEN,access_token,Constant.MINI_ACCESS_TOKEN_TIME);

        return Result.success(access_token);
    }

    /**
     * 图片检测 V2
     * @return
     */
    public Result testingImage(String image) throws Exception{

        //redis获取缓存
        Object cache_access_token = RedisUtil.get(Constant.MINI_ACCESS_TOKEN);

        JSONObject param = new JSONObject();
        param.put("app_id", byteMiniApp.getAppid());
        param.put("access_token", cache_access_token);
        param.put("image", image);

        System.out.println(JSON.toJSONString(param));

        String baseDataStr = HttpClientUtil.sendPostReq("https://developer.toutiao.com/api/apps/censor/image",param,null);

        log.info("接口返回结果  =========== {}",baseDataStr);

        JSONObject baseDataObject = JSON.parseObject(baseDataStr);

        if(baseDataObject.getIntValue("error") != 0){
            log.info("bad access_token req => {} , res => {}", JSON.toJSONString(param), baseDataStr);
            log.info("bad access_token req cache_access_token => {}", cache_access_token);

            return Result.failure(ResultCode.WEB_400,baseDataObject.getBigInteger("error"));
        }

        JSONArray predicts = baseDataObject.getJSONArray("predicts");

        int size = predicts.size();
        for (int i = 0; i < size; i++) {
            JSONObject obj = predicts.getJSONObject(i);
            if(obj.getBoolean("hit")){
                return Result.failure(ResultCode.IMAGE_FAIL,true);
            }
        }

        return Result.success();
    }


    public String antidirt(JSONObject jsonObject) throws IOException {

        getAccessToken();

        //redis获取缓存
        Object cache_access_token = RedisUtil.get(Constant.MINI_ACCESS_TOKEN);

        String body = "";

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://developer.toutiao.com/api/v2/tags/text/antidirt");
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");

        httpPost.setEntity(s);
        httpPost.setHeader("X-Token", String.valueOf(cache_access_token));
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, HTTP.UTF_8);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();

        return body;
    }

    public static boolean isJson(String str) {
        boolean result = false;
        try {
            Object obj = JSON.parse(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }


}
